WorkerScript.onMessage = function(message) {
    doLoadActivities(message);
}


function doLoadActivities(message) {
    var j = 0;
    var k = 0;
    var lastUserName = "";
    var xhr = new XMLHttpRequest;

    var url = "https://production-2.sogeoapi.com/api/users/activity_feed?page=" + message.page + "&per_page=" + message.g.perPage + "&oauth_token=" + message.token;
    xhr.open("GET", url);
    xhr.onreadystatechange = function() {
        try {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                message.model.clear();
                var alltext = JSON.parse(xhr.responseText);
                for (var i in alltext.data) {
                    var activity = alltext.data[i].activity_feed;
                    var client = activity.client_application ? activity.client_application.name : "unknown client";
                    message.model.append({
                              user_name: activity.user_name,
                              message: activity.message,
                              avatarUrl: getAvatar(activity.user_avatar),
                              accessoryUrl: getAccessory(activity.object_avatar),
                              type: activity.object_type,
                              when: activity.created_at,
                              index: i,
                              client: client,
                              user_id: activity.user_id,
                              poi_id: activity.poi_id
                           });
                }
                message.model.sync();
                WorkerScript.sendMessage({ 'result': 'SUCCESS', 'listState': '' });
            }
        } catch(err) {
            WorkerScript.sendMessage({ 'result': 'FAILURE', 'message': err, 'listState': '' });
        }
    }
    xhr.send();

}

function getAvatar(avatar) {

    if (avatar) {
        return avatar; //.substring(0, avatar.indexOf("?"));
    } else {
        return "../Images/avatar-placeholder.png";
    }
}

function getAccessory(avatar) {
    if (avatar) {
        return avatar.substring(0, avatar.indexOf("?"));;
    } else {
        return "";
    }
}


